package com.ysstech.common.util.imgutil;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Remark:<br>
 */
public class ImageUtil {

    private static final Logger logger = LoggerFactory.getLogger(ImageUtil.class);

    @SuppressWarnings("serial")
    public final static Map<String, String> imageTypeMap = new HashMap<String, String>() {{
        put("ffd8", "jpg");// 兼容jpeg
        put("4749", "gif");
        put("0000", "ico");
        put("8950", "png");
        put("424d", "bmp");
    }};

    private static String bytesToHexString(byte[] src) throws Exception {
        StringBuilder buffer = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                buffer.append(0);
            }
            buffer.append(hv);
        }
        return buffer.toString();
    }

    public static String isRealImage(byte[] imageData) throws Exception {
        if (imageData == null || imageData.length < 2) {
            return null;
        }
        try {
            byte[] bt = new byte[2];
            bt[0] = imageData[0];
            bt[1] = imageData[1];
            String type = bytesToHexString(bt);
            return imageTypeMap.get(type);
        } catch (Exception ex) {
            logger.error("判断图片出错"+ex.toString());
            throw new Exception(ex);
        }
    }

    public static String isRealImage(String imagePath) throws Exception {
        if (StringUtils.isBlank(imagePath)) {
            return null;
        }
        InputStream is = null;
        try {
            is = new FileInputStream(new File(imagePath));
            byte[] bt = new byte[2];
            is.read(bt);
            return isRealImage(bt);
        } catch (Exception ex) {
            logger.error("判断图片出错"+ex.toString());
            throw new Exception(ex);
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

}
